package cn.b.sky.admin.security.context;

import org.springframework.util.Assert;

/**
 * 
 * <strong>Title : InheritableThreadLocalManagementContextHolderStrategy.java<br></strong>
 * <strong>Package : cn.b.sky.admin.security.context<br></strong>
 * <strong>Description : </strong>子线程共享<br> 
 * <strong>Create on : 2016-12-19 上午10:34:50<br></strong>
 * <p>
 * @author lidapeng<br>
 * @version <strong>v1.0.0</strong><br>
 * <br>
 * <strong>修改历史:</strong><br>
 * 修改人|修改日期|修改描述<br>
 * -------------------------------------------<br>
 * <br>
 * <br>
 */
public class InheritableThreadLocalManagementContextHolderStrategy implements ManagementContextHolderStrategy {

  //~ Static fields/initializers =====================================================================================

  private static final ThreadLocal<ManagementContext> contextHolder = new InheritableThreadLocal<ManagementContext>();

  //~ Methods ========================================================================================================

  @Override
  public void clearContext() {
      contextHolder.remove();
  }

  @Override
  public ManagementContext getContext() {
      ManagementContext ctx = contextHolder.get();

      if (ctx == null) {
          ctx = createEmptyContext();
          contextHolder.set(ctx);
      }

      return ctx;
  }

  @Override
  public void setContext(ManagementContext context) {
      Assert.notNull(context, "Only non-null ManagementContext instances are permitted");
      contextHolder.set(context);
  }

  @Override
  public ManagementContext createEmptyContext() {
    return new ManagementContextImpl();
  }

}
